#include "slm_j_parm_t.h"
#include "at_slm332.h"

//提供设置MQTT 客户端的处理接口
extern uint8_t get_mg_mqttc_number(void);
extern void set_mg_mqtt_setup(uint8_t setup);
//替换strcpy
static int j_t_slm_factory(void* pram_node, uint16_t parm_size, void* arg) {
    if (pram_node == NULL) {
        return -1;
    }
    slm_cfg_t* cfg = pram_node;
    cfg->slm_status = slm_power_down;
		set_mg_mqtt_setup(4);
    for (int i = 0; i < get_mg_mqttc_number(); i++) {
        // 使用 snprintf 替代 strcpy，并确保缓冲区安全
        snprintf(cfg->smqtt[i].txt, sizeof(cfg->smqtt[i].txt), "mqtt_client");
        snprintf(cfg->smqtt[i].client_id, sizeof(cfg->smqtt[i].client_id), "pc122%d", i);  
        snprintf(cfg->smqtt[i].user_name, sizeof(cfg->smqtt[i].user_name), "admin");
        snprintf(cfg->smqtt[i].pass_word, sizeof(cfg->smqtt[i].pass_word), "admin");
        snprintf(cfg->smqtt[i].host, sizeof(cfg->smqtt[i].host), "broker.emqx.io");
        cfg->smqtt[i].port = 1883;
        snprintf(cfg->smqtt[i].subtopic, sizeof(cfg->smqtt[i].subtopic), "ddjia%d", i);    
        snprintf(cfg->smqtt[i].pubtopic, sizeof(cfg->smqtt[i].pubtopic), "ppjia%d", i);    
        cfg->smqtt[i].Qos = 0;
    }
    return 0;
}
/*检查设置*/
static int j_t_slm_check (void* pram_node, uint16_t parm_size, void* arg){
    //return -1;// TEST FACTORY
    if(pram_node == NULL){
        return -1;
    }
    slm_cfg_t* cfg = pram_node;
    for(int i=0;i<get_mg_mqttc_number();i++){
    if(cfg->smqtt[i].port < 0 || cfg->smqtt[i].port > 65535){
        return -1;
    }
	 }
    /*ok */
    return 0;

}
/*应用设置*/
static int j_t_slm_apply (void* pram_node, uint16_t parm_size, void* arg){
    if(pram_node == NULL){
        return -1;
    }
    slm_cfg_t* cfg = pram_node;
    /*应用设置*/
		for(int i=0;i<get_mg_mqttc_number();i++){
    strcpy(slm_cfg.smqtt[i].txt, cfg->smqtt[i].txt);
    strcpy(slm_cfg.smqtt[i].client_id, cfg->smqtt[i].client_id);
    strcpy(slm_cfg.smqtt[i].user_name, cfg->smqtt[i].user_name);
    strcpy(slm_cfg.smqtt[i].pass_word, cfg->smqtt[i].pass_word);
    strcpy(slm_cfg.smqtt[i].host, cfg->smqtt[i].host);
    slm_cfg.smqtt[i].port = cfg->smqtt[i].port;
    strcpy(slm_cfg.smqtt[i].subtopic, cfg->smqtt[i].subtopic);
    strcpy(slm_cfg.smqtt[i].pubtopic, cfg->smqtt[i].pubtopic);
    slm_cfg.smqtt[i].Qos = cfg->smqtt[i].Qos;
	   }
    //状态不需要设置，直接读取
    //slm_cfg.slm_status = cfg_t->slm_status;
    return 0;
}

/*j_parm使用的数据, 打包当前设置参数和函数*/
const j_parm_user_data_t j_parm_t_slm_p = {
    .parm = &slm_cfg,
    .parm_size = sizeof(slm_cfg_t),
    .op_factory = j_t_slm_factory,
    .op_check = j_t_slm_check,
    .op_apply = j_t_slm_apply,
};